<!--  -->
<template>
  <div id="login">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      class="demo-ruleForm"
    >
      <el-form-item prop="username">
        <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          v-model="ruleForm.password"
          type="password"
          autocomplete="off"
        />
      </el-form-item>

      <el-form-item id="btn">
        <el-button type="primary" @click="loginFn()">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang='ts' setup>
import { reactive, toRefs, ref } from "vue";
import { adminLoginApi, getAdminInfoApi } from "../../request/api";
import Cookies from "js-cookie";
import { useRouter } from "vue-router";

const state = reactive({
  ruleForm: {
    username: "admin",
    password: "123456",
  },
});

const validatePwd = (
  rule: unknown,
  value: string | undefined,
  cb: (msg?: string) => void
) => {
  if (!value) {
    cb("密码不能为空");
  } else {
    cb();
  }
};

// 校验规则
const rules = reactive({
  username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  password: [{ validator: validatePwd, trigger: "blur" }],
});

let { ruleForm } = toRefs(state);

// 获取
const ruleFormRef = ref();
// 获取项目路由对象
let router = useRouter();

// 登录事件
const loginFn = () => {
  ruleFormRef.value
    .validate()
    .then(() => {
      console.log("校验通过");
      adminLoginApi({
        password: ruleForm.value.password,
        username: ruleForm.value.username,
      }).then((res) => {
        if (res.code == 200) {
          // 存储token
          Cookies.set("token", res.data.tokenHead + res.data.token, {
            expires: 7,
          });
          // 获取用户信息
          getAdminInfoApi().then((res) => {
            if (res.code == 200) {
              // 路由跳转
              router.push("/homepage");
            }
          });
        }
      });
    })
    .catch(() => {
      console.log("校验失败");
    });
};
</script>

<style lang='less' scoped>
#login {
  width: 300px;
  margin: 0 auto;
  margin-top: 300px;
}

button:hover {
  border-color: #646cff;
}

button:focus,
button:focus-visible {
  outline: 4px auto -webkit-focus-ring-color;
}

button {
  border-radius: 8px;
  border: 1px solid transparent;
  padding: 0.6em 1.2em;
  font-size: 1em;
  font-weight: 500;
  font-family: inherit;
  background-color: #1a1a1a;
  cursor: pointer;
  transition: border-color 0.25s;
  background-color: #576fce;
  width: 100%;
  // margin: 0 50px;
}

// @media (prefers-color-scheme: light) {
//   :root {
//     color: #213547;
//     background-color: #ffffff;
//   }
//   a:hover {
//     color: #747bff;
//   }
//   button {
//     background-color: #576fce;
//   }
// }
</style>